package com.local.cart.controller;

import com.local.cart.pojo.ShoppingCart;
import com.local.cart.service.ShoppingCartService;
import com.local.common.constants.CommonConstants;
import com.local.common.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.ToIntFunction;

/**
 * 购物车控制器
 */
@Controller
@RequestMapping("/cart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询用户的购物车列表
     * @return
     */
    @GetMapping("/list/{userId}")
    @ResponseBody
    public ResultUtil getListByUserId(@PathVariable("userId") Integer userId) {
        List<ShoppingCart> cartList = shoppingCartService.getListByUserId(userId);
        if (Objects.isNull(cartList)) {
            return new ResultUtil(201, "请求失败，请稍后再试");
        } else {
            return new ResultUtil(200, "", cartList);
        }
    }


    /**
     * 加入购物车
     * @param shoppingCart：数据中包含 userId 字段
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultUtil<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        Integer addResult = shoppingCartService.addToShoppingCart(shoppingCart);
        if (addResult > 0) {
            return new ResultUtil(200, "加入购物车成功", shoppingCart);
        } else {
            return new ResultUtil(201, "加入购物车失败，请稍后再试");
        }
    }


    /**
     * 在购物车页面，删除某个商品
     * @return
     */
    @DeleteMapping("/{cartItemId}")
    @ResponseBody
    public ResultUtil delete(@PathVariable("cartItemId") Integer cartItemId) {
        Integer result = shoppingCartService.deleteByCartItemId(cartItemId);
        if (result > 0) {
            return new ResultUtil(200, "删除成功");
        } else {
            return new ResultUtil(201, "删除失败");
        }
    }


    /**
     * 在购物车页面，修改商品数量
     * @return
     */
    @PutMapping
    @ResponseBody
    public ResultUtil updateGoodsCount(@RequestBody ShoppingCart shoppingCart) {
        Integer result = shoppingCartService.updateGoodsCount(shoppingCart);
        if (result > 0) {
            return new ResultUtil(200, "数量修改成功");
        } else {
            return new ResultUtil(201, "数量修改失败，请稍后再试");
        }
    }
}
